package com.nacl.upload.service.impl;

import com.nacl.upload.po.UploadTask;
import com.nacl.upload.service.AsyncUploadService;
import com.nacl.upload.service.MyUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @description: 异步处理
 * @author: xukang
 * @create: 2025-08-01
 */
@Service
public class MyUploadServiceImpl implements MyUploadService {

    @Autowired
    private AsyncUploadService uploadService;

    @Override
    public void upload(MultipartFile file, UploadTask uploadTask) {
        LinkedHashMap<String,String> errorMap = new LinkedHashMap<>();
        uploadTask.setStatus(UploadTask.TaskStatus.FAILURE);
        try{
            // todo 自行处理文件
            Thread.sleep(1000*10);
            System.out.println("自行处理文件");

            // 模拟随机处理
            if (uploadTask.getId() % 3 == 0) {
                uploadTask.setStatus(UploadTask.TaskStatus.SUCCESS);
                uploadTask.setTotalRows(100);
                uploadTask.setSuccessRows(100);
            } else {
                uploadTask.setTotalRows(100);
                uploadTask.setSuccessRows(99);
                uploadTask.setFailureRows(1);
                errorMap.put("第10行","错误原因：.........");
                uploadTask.setErrorMessage(errorMap);
            }

        }catch (Exception e){
            // 失败处理
            errorMap.put("错误",e.getMessage());
            uploadTask.setErrorMessage(errorMap);
        }
        // 保存最终状态
        uploadService.storageSave(uploadTask);
    }

}
